﻿using System;
using NUnit.Core;
using SeleniumToolkit.Core;

namespace SeleniumToolkit.NUnit
{
    /// <summary>
    /// EventListener extension for NUnit.
    /// </summary>
    /// <remarks>
    /// Responsible for launching the java process at the beginning of the test-run
    /// </remarks>
    internal class SeleniumEventListener : EventListener
    {
        readonly ISeleniumProcess _process;

        #region Constructor
        /// <summary>
        /// Default Constructor
        /// </summary>
        /// <param name="process">selenium process</param>
        public SeleniumEventListener(ISeleniumProcess process)
        {
            _process = process;
        } 
        #endregion

        #region EventListener Members

        /// <summary>
        /// EventListener called when Test run completes with an error
        /// </summary>
        /// <param name="exception"></param>
        public void RunFinished(Exception exception)
        {
        }

        /// <summary>
        /// Stops the java process if configured to autostop
        /// </summary>
        /// <param name="result"></param>
        public void RunFinished(TestResult result)
        {
            if (_process == null) return;

            if (AutoStart && AutoStop)
            {
                _process.Stop();
            }
        }

        /// <summary>
        /// Starts the java process if configure to autostart
        /// </summary>
        /// <param name="name"></param>
        /// <param name="testCount"></param>
        public void RunStarted(string name, int testCount)
        {
            if (_process == null) return;

            if (testCount > 0 && WebTestsPresent)
            {
                if (AutoStart)
                {
                    _process.Start();
                }
            }
        }

        public void SuiteFinished(TestResult result)
        {
        }

        public void SuiteStarted(TestName testName)
        {
        }

        public void TestFinished(TestResult result)
        {
        }

        public void TestOutput(TestOutput testOutput)
        {
        }

        public void TestStarted(TestName testName)
        {
        }

        public void UnhandledException(Exception exception)
        {
        }

        #endregion

        /// <summary>
        /// Flag to indicate whether the test runner has tests present
        /// </summary>
        /// <remarks>When set to true, the event listener will kick off a selenium-rc instance</remarks>
        internal static bool WebTestsPresent
        {
            get;
            set;
        }

        public bool AutoStart
        {
            get;
            set;
        }

        public bool AutoStop
        {
            get;
            set;
        }
    }
}
